from fastapi import APIRouter, BackgroundTasks, Depends, Request
from starlette.responses import HTMLResponse
from tortoise.expressions import Q

from applications.common.render_template import templates
from applications.common.user_manager import manager, permission_depends
from applications.utils.http import ResultResponse, fail_api, success_api, table_api
from applications.utils.send_mail import EmailService
from applications.models import Mail, User
from applications.schemas.admin_mail import MailOutSchema, MailQueryModel, MailSaveModel

route = APIRouter(prefix="/mail", tags=["系统管理-邮件管理"])


# 邮件管理
@route.get(
    "/",
    dependencies=[Depends(permission_depends("system:mail:main"))],
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def main(request: Request):
    return templates.TemplateResponse("system/mail/main.html", {"request": request})


# 邮件分页查询
@route.get("/data", dependencies=[Depends(permission_depends("system:mail:main"))], summary="获取邮件列表")
async def get_mail_list(data: MailQueryModel = Depends()):
    # 查询参数构造
    query = Q()
    if data.receiver:
        query &= Q(receiver__icontains=data.receiver)
    if data.subject:
        query &= Q(subject__icontains=data.subject)
    if data.content:
        query &= Q(content=data.content)

    # orm查询
    mails = (
        await Mail.filter(query).offset((data.page - 1) * data.limit).limit(data.limit).prefetch_related("user").all()
    )
    count = await Mail.filter(query).count()

    # 处理数据
    data = []
    for mail in mails:
        mail_dict = MailOutSchema.model_validate(mail).model_dump()
        if hasattr(mail, "user") and mail.user:
            mail_dict["realname"] = mail.user.realname
        data.append(mail_dict)

    return table_api(data=data, count=count)


# 邮件增加页面
@route.get(
    "/add",
    dependencies=[Depends(permission_depends("system:mail:add"))],
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def add(request: Request):
    return templates.TemplateResponse("system/mail/add.html", {"request": request})


@route.post(
    "/save",
    dependencies=[Depends(permission_depends("system:mail:add"))],
    summary="保存邮件",
    response_model=ResultResponse,
)
async def save(data: MailSaveModel, background_tasks: BackgroundTasks, user: User = Depends(manager)):
    # 实际项目中这里应该调用真实的邮件发送服务
    background_tasks.add_task(send_mail, data=data, user_id=user.id)
    return success_api(msg="邮件已发送")


async def send_mail(data: MailSaveModel, user_id: int):
    # 注意：这里简化了邮件发送逻辑，实际项目中应该实现真实的邮件发送功能
    mail = Mail(receiver=data.receiver, subject=data.subject, content=data.content, user_id=user_id)
    try:
        service = EmailService()
        await service.send_text(recipients=data.receiver, subject=data.subject, text=data.content)
        await mail.save()
    except Exception as e:
        mail.exception = str(e)
        mail.is_success = False
        await mail.save()


# 删除邮件
@route.delete(
    "/remove/{pk}",
    dependencies=[Depends(permission_depends("system:mail:remove"))],
    summary="删除邮件",
    response_model=ResultResponse,
)
async def delete(pk: int):
    mail = await Mail.get_or_none(id=pk)
    if not mail:
        return fail_api(msg="删除失败")

    await mail.delete()
    return success_api(msg="删除成功")


# 批量删除
@route.delete(
    "/batchRemove",
    dependencies=[Depends(permission_depends("system:mail:remove"))],
    summary="批量删除邮件",
    response_model=ResultResponse,
)
async def batch_remove(ids: list[int]):
    await Mail.filter(id__in=ids).delete()
    return success_api(msg="批量删除成功")
